package com.woshua.knifelibrary;

import android.app.Activity;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;

import com.woshua.knifelibrary.adapter.InjectAdapter;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ButterView {
    static Map<Class<?>, InjectAdapter<?>> sInjectCache = new HashMap();

    public ButterView() {
    }

    public static void inject(Activity activity) {
        InjectAdapter adapter = getViewAdapter(activity.getClass());
        adapter.injects(activity);
    }

    public static void inject(Fragment fragment, View rootView) {
        InjectAdapter adapter = getViewAdapter(fragment.getClass());
        if(fuckTheFragment(fragment, rootView)) {
            adapter.injects(fragment);
        }
    }

    private static boolean fuckTheFragment(Fragment fragment, View rootView) {
        try {
            Class e;
            for(e = fragment.getClass(); e != Object.class && !e.equals(Fragment.class); e = e.getSuperclass()) {
                ;
            }

            Field rootViewField = e.getDeclaredField("mView");
            rootViewField.setAccessible(true);
            rootViewField.set(fragment, rootView);
            Log.e("", "### getView " + fragment.getView());
            return true;
        } catch (SecurityException var4) {
            var4.printStackTrace();
        } catch (NoSuchFieldException var5) {
            var5.printStackTrace();
        } catch (IllegalArgumentException var6) {
            var6.printStackTrace();
        } catch (IllegalAccessException var7) {
            var7.printStackTrace();
        }

        return false;
    }

    public static void inject(View view) {
    }

    private static <T> InjectAdapter<T> getViewAdapter(Class<?> clazz) {
        InjectAdapter adapter = (InjectAdapter)sInjectCache.get(clazz);
        if(adapter == null) {
            String adapterClassName = clazz.getName() + "$ViewAdapter";

            try {
                Class e = Class.forName(adapterClassName);
                adapter = (InjectAdapter)e.newInstance();
                sInjectCache.put(e, adapter);
            } catch (ClassNotFoundException var4) {
                var4.printStackTrace();
            } catch (InstantiationException var5) {
                var5.printStackTrace();
            } catch (IllegalAccessException var6) {
                var6.printStackTrace();
            }
        }

        Log.e("", "### find adapter : " + adapter);
        return (InjectAdapter)adapter;
    }

}
